import requests
import json


def call_llm_api(question: str):
    url = "http://localhost:3000/LLM"
    headers = {"Content-Type": "application/json"}
    data = {"question": question}

    try:
        with requests.post(url, headers=headers, json=data, stream=True) as response:
            response.raise_for_status()

            for line in response.iter_lines():
                if line:
                    decoded_line = line.decode('utf-8')
                    if decoded_line.startswith("data:"):
                        json_str = decoded_line[5:].strip()
                        try:
                            event = json.loads(json_str)
                            if event.get('type') == 'result':
                                print(event)
                            elif event.get('type') == 'content':
                                print(f"收到内容: {event['content']}")
                            elif event.get('type') == 'error':
                                print(f"发生错误: {event['error']}")
                            # 处理其他类型事件
                        except json.JSONDecodeError:
                            print(f"无法解析的响应: {json_str}")

    except requests.exceptions.RequestException as e:
        print(f"请求失败: {str(e)}")


if __name__ == "__main__":
    # 示例调用
    call_llm_api("江海货368 2025年2月20日航行记录。")